package net.cyue.homework.student.management.servlet.student;


import jakarta.servlet.annotation.WebServlet;
import jakarta.validation.Valid;
import net.cyue.homework.student.management.dto.DeleteDTO;
import net.cyue.homework.student.management.entity.Student;
import net.cyue.homework.student.management.http.HTTPServlet;
import net.cyue.homework.student.management.http.WebResult;
import net.cyue.homework.student.management.http.annotation.DeleteMethod;
import net.cyue.homework.student.management.http.annotation.PostMethod;
import net.cyue.homework.student.management.http.annotation.PutMethod;
import net.cyue.homework.student.management.util.DB;
import net.cyue.nest.nestjava.common.annotation.Body;
import net.cyue.nest.nestjava.common.annotation.Response;
import net.cyue.nest.nestjava.common.enums.HTTPStatus;
import net.cyue.nest.nestjava.common.interfaces.http.IHTTPRequest;
import net.cyue.nest.nestjava.common.interfaces.http.IHTTPResponse;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet(
    name = "StudentServlet",
    value = {
        "/api/student",
        "/api/student/"
    }
)
public class StudentServlet extends HTTPServlet {

    public Student selectStudent(int id) throws SQLException {
        ResultSet resultSet = DB.POOL.query("select * from student where student_id = " + id + " limit 1");
        if (!resultSet.next()) {
            return null;
        }
        Student student = new Student(
            resultSet.getInt("student_id"),
            resultSet.getString("name"),
            resultSet.getString("gender"),
            resultSet.getInt("major_id"),
            resultSet.getInt("class_id"),
            resultSet.getInt("job_id"),
            resultSet.getString("phone"),
            resultSet.getDate("birthday")
        );
        resultSet.close();
        return student;
    }

    private int insertStudent(Student student) throws SQLException {
        return DB.POOL.transactionPreparedUpdate(
            "INSERT INTO student (student_id, name, gender, major_id, class_id, job_id, phone, birthday) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
            new Object[]{
                student.getStudentId(),
                student.getName(),
                student.getGender(),
                student.getMajorId(),
                student.getClassId(),
                student.getJobId(),
                student.getPhone(),
                student.getBirthday()
            }
        );
    }
    private int updateStudent(Student student) throws SQLException {
        return DB.POOL.transactionPreparedUpdate(
            "UPDATE student SET name = ?, gender = ?, major_id = ?, class_id = ?, job_id = ?, phone = ?, birthday = ? WHERE student_id = ?",
            new Object[]{
                student.getName(),
                student.getGender(),
                student.getMajorId(),
                student.getClassId(),
                student.getJobId(),
                student.getPhone(),
                student.getBirthday(),
                student.getStudentId()
            }
        );
    }

    @Override
    public void doGet(
        IHTTPRequest request,
        IHTTPResponse response
    ) throws IOException {
        String studentID = request.getParameter("id");
        if (studentID == null || studentID.isEmpty()) {
            response.code(HTTPStatus.BAD_REQUEST);
            response.send("id is required");
            return;
        }
        try {
            Student student = selectStudent(Integer.parseInt(studentID));
            if (student == null) {
                response.code(HTTPStatus.NOT_FOUND);
                response.send(WebResult.failed("学生不存在"));
                return;
            }
            response.send(WebResult.success("获取成功", student));
        } catch (SQLException e) {
            e.printStackTrace();
            response.code(HTTPStatus.INTERNAL_SERVER_ERROR);
            response.send(WebResult.failed("内部错误，获取失败"));
        }
    }

    @PostMethod
    public void addStudent(
        @Response IHTTPResponse response,
        @Valid @Body Student student
    ) throws IOException {
        try {
            int rows = this.insertStudent(student);
            if (rows == 0) {
                response.code(HTTPStatus.BAD_REQUEST);
                response.send(WebResult.failed("添加失败"));
                return;
            }
            response.send(WebResult.success("添加成功"));
        } catch (SQLException e) {
            e.printStackTrace();
            response.code(HTTPStatus.INTERNAL_SERVER_ERROR);
            response.send(WebResult.failed("内部错误，添加失败"));
        }
    }


    @PutMethod
    public void doPut(
        @Response IHTTPResponse response,
        @Valid @Body Student student
    ) throws IOException {
        try {
            int rows = this.updateStudent(student);
            if (rows == 0) {
                response.code(HTTPStatus.BAD_REQUEST);
                response.send(WebResult.failed("更新失败"));
                return;
            }
            response.send(WebResult.success("更新成功"));
        } catch (SQLException e) {
            e.printStackTrace();
            response.code(HTTPStatus.INTERNAL_SERVER_ERROR);
            response.send(WebResult.failed("内部错误，更新失败"));
        }
    }


    @DeleteMethod
    public void doDelete(
        @Response IHTTPResponse response,
        @Valid @Body DeleteDTO dto
    ) throws IOException {
        try {
            int rows = DB.POOL.transactionPreparedUpdate(
                "DELETE FROM student WHERE student_id = ?",
                new Object[]{dto.getId()}
            );
            if (rows == 0) {
                response.code(HTTPStatus.BAD_REQUEST);
                response.send(WebResult.failed("删除失败"));
                return;
            }
            response.send(WebResult.success("删除成功"));
        } catch (SQLException e) {
            response.code(HTTPStatus.INTERNAL_SERVER_ERROR);
            response.send(WebResult.failed("内部错误，删除失败"));
        }
    }

}


